//
//  RegisteViewController.m
//  ChatDemo-UI2.0
//
//  Created by li.guibin on 15/12/1.
//  Copyright © 2015年 li.guibin. All rights reserved.
//

#import "RegisteViewController.h"
//#import "WebViewController.h"

@interface RegisteViewController ()<UIAlertViewDelegate>
@property (weak, nonatomic) IBOutlet UITextField *registeName;
@property (weak, nonatomic) IBOutlet UITextField *registePhoneNum;
@property (weak, nonatomic) IBOutlet UITextField *verificationCode;
@property (weak, nonatomic) IBOutlet UITextField *registePassword;
@property (weak, nonatomic) IBOutlet UITextField *comfirmPassword;
@property (weak, nonatomic) IBOutlet UIButton *verificationBtn;
@property (weak, nonatomic) IBOutlet UIButton *registeBtn;
@property (weak, nonatomic) IBOutlet UIButton *agreetServiceBtn;
@property (nonatomic, assign)BOOL isAgreet;
@end

@implementation RegisteViewController

@synthesize isAgreet;
- (void)viewDidLoad {
    [super viewDidLoad];
    UIButton *backButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 44, 44)];
    [backButton setImage:[UIImage imageNamed:@"back.png"] forState:UIControlStateNormal];

    [backButton addTarget:self.navigationController action:@selector(popViewControllerAnimated:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    [self.navigationItem setLeftBarButtonItem:backItem];

    _verificationBtn.layer.cornerRadius = 5.0f;
    _registeBtn.layer.cornerRadius = 5.0f;
    
    
    //数据限制
    _registeName.delegate=self;
    [_registeName addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    
    _registePhoneNum.delegate=self;
    [_registePhoneNum addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    _registePhoneNum.keyboardType=UIKeyboardTypeNumberPad;
    
    _verificationCode.delegate=self;
    [_verificationCode addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    
    _registePassword.delegate=self;
    [_registePassword addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    
    _comfirmPassword.delegate=self;
    [_comfirmPassword addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    // Do any additional setup after loading the view.
}


- (IBAction)agreetAction:(UIButton *)sender {
    if (isAgreet)
    {
        isAgreet = NO;
        [_agreetServiceBtn setImage:[UIImage imageNamed:@"无对勾"] forState:UIControlStateNormal];
    }else
    {
        isAgreet = YES;
        [_agreetServiceBtn setImage:[UIImage imageNamed:@"对勾"] forState:UIControlStateNormal];
    }
    
    
}
- (IBAction)readServiceAgreement:(UIButton *)sender {
//    WebViewController * webView = [[WebViewController alloc]init];
//    webView.controllerTitle = @"服务协议";
//    webView.requestURL = @"http://api.our100.net/ServiceProtocols.aspx";
//    [self.navigationController pushViewController:webView animated:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)verify:(id)sender {
    
    if (_registePhoneNum.text.length != 11) {
        [Utils alertViewWithMessage:@"请填写正确手机号"];
        return;
    }
    NSMutableDictionary * dict = [[NSMutableDictionary alloc] initWithCapacity:0];
    [dict setObject:@"api_VerifyCode_get" forKey:@"method"];
    [dict setObject:@"0" forKey:@"Type"];
    [dict setObject:_registePhoneNum.text forKey:@"Mobile"];
    [Utils get:nil parameters:dict success:^(NSInteger recode ,id jsonObject){
        NSLog(@"%@", jsonObject);
       //60s倒计时
        /*启动计时器*/
        self->ti= [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerFireMethod:) userInfo:nil repeats:YES];
        self->time=60;
        
        self->_verificationBtn.enabled=NO;
        
        
        [self->_verificationBtn setBackgroundColor:[Utils stringToColor:@"dddddd"]];
        [self->_verificationBtn setTitleColor:[Utils stringToColor:@"979797"] forState:UIControlStateNormal];
        [self->_verificationBtn setTitle:[NSString stringWithFormat:@"等待%d秒",self->time] forState:UIControlStateNormal];

    } failure:^(NSInteger recode, NSError * error){
      //请求失败错误处理
        
    }];
    
}
/**
 *  编辑人：张东海
 *  时间：2016年5月26日
 *  更改或添加内容：计时器调用方法
 *  备注：
 */

-(void)timerFireMethod:(NSTimer *)timer{
    
    time-=1;
    [self->_verificationBtn setTitle:[NSString stringWithFormat:@"等待%d秒",time] forState:UIControlStateNormal];
    // lab.text=[NSString stringWithFormat:@"等待%d秒",time];
    if (time==0) {
        self->_verificationBtn.enabled=YES;
        
        
        [self->_verificationBtn setBackgroundColor:[Utils stringToColor:@"fffbb5"]];
        [self->_verificationBtn setTitleColor:[Utils stringToColor:@"ae7d3d "] forState:UIControlStateNormal];
        
        
        [self->_verificationBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
        if ([timer isValid] == YES) {
            [timer invalidate];
            timer = nil;
        }
        
    }
    
}

- (IBAction)registe:(id)sender {
    
    
    if ([[_registeName.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length]==0) {
        
        [Utils alertViewWithMessage:@"请输入昵称"];
        return;
    }

    
    BOOL contains = [Utils stringContainsEmoji:_registeName.text];
    if (contains) {
        
        [Utils alertViewWithMessage:@"昵称中不能含有特殊字符"];
        return;
    }
    
    if (!isAgreet) {
        [Utils alertViewWithMessage:@"请先同意服务协议"];
        return;
    }
    
    if (_registePhoneNum.text.length == 0||_verificationCode.text.length == 0 ||[[_registePassword.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length]==0|| [[_comfirmPassword.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length]==0){
        
        [Utils alertViewWithMessage:@"请将信息填写完整"];
        return;
    }
    
    if (_registeName.text.length>8) {
        [Utils alertViewWithMessage:@"请将昵称限制在8个字以内"];
        return;
    }

    if (_registePassword.text.length < 6 || _registePassword.text.length > 16) {
        [Utils alertViewWithMessage:@"请将密码限制在6-16位以内"];
        return;
    }
    
    if (_comfirmPassword.text.length < 6 || _comfirmPassword.text.length > 16) {
        
         [Utils alertViewWithMessage:@"请将确认密码限制在6-16位以内"];
        return;
    }
    
    if (![_registePassword.text isEqualToString:_comfirmPassword.text]) {
        [Utils alertViewWithMessage:@"两次输入密码不一致"];
        return;
    }
    
    NSMutableDictionary * dict = [[NSMutableDictionary alloc] initWithCapacity:0];
    [dict setObject:@"api_user_register" forKey:@"Method"];
    [dict setObject:_verificationCode.text forKey:@"verify"];
    [dict setObject:_registePhoneNum.text forKey:@"mobile"];
    [dict setObject:_registeName.text forKey:@"username"];
    [dict setObject:[Utils MD5EncryptWith:_registePassword.text] forKey:@"userpass"];
    
    [Utils get:nil parameters:dict success:^(NSInteger recode ,id jsonObject){
        NSDictionary * dict = (NSDictionary *)jsonObject;
        NSString *message = [dict objectForKey:@"re_info"];
        
        
        NSDictionary * personalImformation = [dict objectForKey:@"re_data"];
        BOOL save = [SyUserInfomation personalImformationSaveWtih:personalImformation];
        NSLog(@"save status 1 is success 0 is failture :%i",save);
        
        //NSDictionary * userinfo = [personalImformation objectForKey:@"userinfo"];
        //NSString * userID = [NSString stringWithFormat:@"%@",[userinfo objectForKey:@"userid"]];

        //[[NSUserDefaults standardUserDefaults] setObject:userID forKey:@"userid"];

        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:message delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alert show];
        
    } failure:^(NSInteger recode, NSError * error){
    }];
}



- (void)textFieldDidChange:(UITextField *)textField
{
    
    if (textField == _registeName) {
        
        if (_registeName.text.length > 8) {
            UITextRange *markedRange = [_registeName markedTextRange];
            if (markedRange) {
                return;
            }
            //Emoji占2个字符，如果是超出了半个Emoji，用15位置来截取会出现Emoji截为2半
            //超出最大长度的那个字符序列(Emoji算一个字符序列)的range
            NSRange range = [_registeName.text rangeOfComposedCharacterSequenceAtIndex:8];
            _registeName.text = [_registeName.text substringToIndex:range.location];
        }
        
    }else if (textField==_registePhoneNum)
    {
        if (textField.markedTextRange == nil && textField.text.length >11) {
            textField.text = [textField.text substringToIndex:11];

        }
    
    }else if (textField==_verificationCode)
    {
        if (textField.markedTextRange == nil && textField.text.length >6) {
            textField.text = [textField.text substringToIndex:6];
        }
    }else if (textField==_registePassword)
    {
        if (_registePassword.text.length > 16) {
            UITextRange *markedRange = [_registePassword markedTextRange];
            if (markedRange) {
                return;
            }
            //Emoji占2个字符，如果是超出了半个Emoji，用15位置来截取会出现Emoji截为2半
            //超出最大长度的那个字符序列(Emoji算一个字符序列)的range
            NSRange range = [_registePassword.text rangeOfComposedCharacterSequenceAtIndex:16];
            _registePassword.text = [_registePassword.text substringToIndex:range.location];
        }

    }else if (textField==_comfirmPassword)
    {
        if (_comfirmPassword.text.length > 16) {
            UITextRange *markedRange = [_comfirmPassword markedTextRange];
            if (markedRange) {
                return;
            }
            //Emoji占2个字符，如果是超出了半个Emoji，用15位置来截取会出现Emoji截为2半
            //超出最大长度的那个字符序列(Emoji算一个字符序列)的range
            NSRange range = [_comfirmPassword.text rangeOfComposedCharacterSequenceAtIndex:16];
            _comfirmPassword.text = [_comfirmPassword.text substringToIndex:range.location];
        }
        
    }
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    NSMutableDictionary *userinfo = [NSMutableDictionary dictionary];
    [userinfo setObject:_registePhoneNum.text forKey:@"phone"];
    [userinfo setObject:_registePassword.text forKey:@"password"];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"registerScuess" object:userinfo];
    [self.navigationController popViewControllerAnimated:YES];
    
}

-(void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextFieldTextDidChangeNotification object:nil];
}

@end
